package com.glela.controller;

import com.alibaba.fastjson.JSONObject;
import com.glela.goods.model.NewsType;
import com.glela.goods.model.vo.NewsVo;
import com.glela.goods.model.vo.TopNewsVo;
import com.glela.goods.model.vo.goods.GoodsPageVo;
import com.glela.goods.service.NewsService;
import com.glela.platform.constant.ErrorEnum;
import com.glela.platform.model.response.ResponseBaseModel;
import com.glela.platform.model.response.ResponsePageModel;
import com.glela.platform.model.response.ResponseResultModel;
import com.glela.platform.util.ParameterUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/news")
public class NewsController extends BaseController{

    @Autowired
    private NewsService newsService;

    @RequestMapping(value = "/getTopNews",method = RequestMethod.POST,consumes = "application/json")
    public ResponseEntity<?> getTopNews(HttpServletRequest request){
        List<TopNewsVo> list = newsService.getTopNews(request);
        return new ResponseEntity<>(new ResponseResultModel<>(list),
                HttpStatus.OK);
    }

    @RequestMapping(value = "/getNewsById",method = RequestMethod.POST,consumes = "application/json")
    public ResponseEntity<?> getTopNews(@RequestBody JSONObject json){
        if (StringUtils.isBlank(json.getString("pageSize"))){
            json.put("pageSize",10);
        }
        if (StringUtils.isBlank(json.getString("pageNum"))){
            json.put("pageNum",1);
        }
        if (ParameterUtils.validParams(json.getString("typeId"))) {
            return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
        }
        int startIndex = (json.getIntValue("pageNum") - 1) * json.getIntValue("pageSize");
        List<NewsVo> list = newsService.getByTypeId(json.getIntValue("typeId"),startIndex,json.getIntValue("pageSize"));
        int count  = newsService.getCountByTypeId(json.getIntValue("typeId"));
        return new ResponseEntity<>(new ResponseResultModel<>(
                new ResponsePageModel<NewsVo>(count, json.getIntValue("pageSize"), json.getIntValue("pageNum"), list)),
                HttpStatus.OK);
    }

    @RequestMapping(value = "/getNewComerCrashType",method = RequestMethod.POST,consumes = "application/json")
    public ResponseEntity<?> getNewComerCrashType(){
        List<NewsType> list = newsService.getNewComerCrashType();
        return new ResponseEntity<>(new ResponseResultModel<>(list),
                HttpStatus.OK);
    }
}
